package co.edu.javeriana.crypto.gui;

import java.awt.TextField;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

/**
 * Clase TextField personalizada para limitar la cantidad de caracteres
 * permitidos.
 */
public class TextFieldWithLimit extends TextField implements KeyListener {
	private static final long serialVersionUID = 1L;
	
	private int maxLength;

	public TextFieldWithLimit(String initialStr, int col, int maxLength) {
		super(initialStr, col);
		this.maxLength = maxLength;
		addKeyListener(this);
	}

	public TextFieldWithLimit(int col, int maxLength) {
		this("", col, maxLength);
	}
	
	public void setMaxLength(int maxLength) {
		this.maxLength = maxLength;
	}
	
	public int getMaxLength() {
		return maxLength;
	}

	public void keyPressed(KeyEvent e) {
		char c = e.getKeyChar();
		int len = getText().length();
		
		if (len < getMaxLength()) {
			return;
		} else {
			if ((c == KeyEvent.VK_BACK_SPACE) || (c == KeyEvent.VK_DELETE)
					|| (c == KeyEvent.VK_ENTER) || (c == KeyEvent.VK_TAB)
					|| e.isActionKey())
				return;
			else {
				e.consume();
			}
		}
	}

	public void keyReleased(KeyEvent e) {
	}

	public void keyTyped(KeyEvent e) {
	}
}